package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    public LoginFilter() {
        // Default constructor
    }

    public void destroy() {
        // Cleanup code if needed
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String path = req.getServletPath();
        String loginURI = req.getContextPath() + "/jsp/login.jsp";
        String loginServletURI = req.getContextPath() + "/loginServlet";

        boolean loggedIn = req.getSession().getAttribute("userName") != null;
        boolean loginRequest = path.equals("/jsp/login.jsp") || path.equals("/loginServlet")|| path.equals("/jsp/register.jsp");

        if (loggedIn || loginRequest || path.startsWith("/resources/")) {
            chain.doFilter(request, response);
        } else {
            req.setAttribute("errorMessage", "您未登录");
            req.getRequestDispatcher("/jsp/login.jsp").forward(req, res);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {
        // Initialization code if needed
    }
}
